package com.xiaodou.mjf.web.console.basic.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xiaodou.mjf.application.basic.service.RoleService;
import com.xiaodou.mjf.application.basic.utils.OperatorUtils;
import com.xiaodou.mjf.entity.basic.Operator;
import com.xiaodou.mjf.entity.basic.Role;
import com.xiaodou.mjf.infrastructure.common.controller.ApplicationController;
import com.xiaodou.mjf.infrastructure.common.utils.StringUtils;

@Controller
@RequestMapping("role")
public class RoleController extends ApplicationController {

	@Resource
    RoleService roleService;


	@RequestMapping(value={"","list"})
	public String list(Model model){
		
		List<Role> roles = OperatorUtils.getRoles();
		
		Operator platform = OperatorUtils.getOperator();
		if(roles!=null) {
			if(platform.getRoles().get(0).getPlatform()!=0) {
				for (int i = roles.size()-1; i >= 0; i--) {
					if(roles.get(i).getPlatform()!=platform.getRoles().get(0).getPlatform()){
						roles.remove(i);
					}
				}
			}
		}
		
		model.addAttribute("roles",roles);
		
		return "security/role/list";
	}
	
	@RequestMapping(value={"form","form/{id}"})
	public String form(Role role,Model model){
        if(StringUtils.isNotBlank(role.getId())){
            role = roleService.get(role.getId());
        }
        model.addAttribute("role",role);
        model.addAttribute("menus",OperatorUtils.getMenus());
		return "security/role/form";
	}
	
	@RequestMapping("save")
	public String save(Role role,Model model){
		if(!beanValidator(model, role)){
			return form(role, model);
		}
		
		roleService.save(role);
		
		return "redirect:/role/list";
	}
}
